package com.eva.ss;

import com.eva.framework.common.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理匿名用户（未登录的用户）
 * 当一个未登录用户发起请求时，在预认证过滤器中不会在Security上下文填充登录用户信息，此时将调用commence方法完成相应。
 */
@Slf4j
@Component
public class DefaultAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("未登录或登录信息已过期");
        ApiResponse.response(response, ApiResponse.failed(HttpStatus.UNAUTHORIZED.value(), "未登录或登录信息已过期"));
    }
}
